﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;


namespace Ehai.Web.Framework.Rules
{
    class SelectRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员
#if DEBUG
        private int _execStatus = -1;
        public int ExecStatus
        {
            get { return _execStatus; }
        }
#endif
        public const string Name = "select";

        /// <summary>
        /// 从数据查询若干条记录
        /// </summary>
        /// <param name="p">
        ///0:（必选）处理类型 select
        ///1:（必选）表名
        ///2:（必选）主键，如果不为一列，则写成id1+id2
        ///3:（可选）使用的连接字符串(id)
        ///4:（可选）列名，多个列名用","隔开，默认 "*"
        ///5:（可选）分组，默认无
        ///6:（可选）分组条件，默认无
        ///7:（可选）排序（可多项）
        ///8:（可选）是否有Language字段，1--有；0--没有
        ///9:（可选）条件
        ///10:（可选）开始条数
        ///11:（可选）条数总数 
        /// </param>
        /// <param name="ci">环境变量ci</param>
        /// <example>
        /// string[] test = {  "select", "DMMessge", "MessageID","EhaiAMS"};      
        /// SelectRule(test, ci);
        /// </example>
        /// string[] test = { "select","DMMessge", "MessageID","EhaiAMS", "MessageID,content,deleteStatus", "", " ", "LatestNodeID desc", "0","", "1", "2" };
        ///  SelectRule(test, ci);
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.WebException:选择规则错误;
        /// </exception>
        /// <returns>
        /// 成功返回查询记录的二维数组;
        /// 基本条件不满足返回null
        /// </returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
            if (p.Length < 3)
            {
#if DEBUG
                // 数组长度没达到要求
                _execStatus = -2;
#endif
                return null;
            }
            if (String.IsNullOrEmpty(p[1]))
            {
#if DEBUG
                // 第一个参数没达到要求
                _execStatus = 1;
#endif
                return null;
            }
            if (String.IsNullOrEmpty(p[2]))
            {
#if DEBUG
                // 第二个参数没达到要求
                _execStatus = 2;
#endif
                return null;
            }
            string p3 = (p.Length > 3 && p[3].Trim() != String.Empty) ? p[3] : String.Empty;
            string p4 = (p.Length > 4 && p[4].Trim() != String.Empty) ? p[4] : "*";              //列名
            string p5 = (p.Length > 5 && p[5].Trim() != String.Empty) ? "group by " + p[5] : String.Empty; //分组
            string p6 = (p.Length > 6 && p[6].Trim() != String.Empty) ? "having " + p[6] : String.Empty;   //分组条件，默认无   
            string p7 = (p.Length > 7 && p[7].Trim() != String.Empty) ? "order by " + p[7] : String.Empty; //排序，可多选中间用","隔开
            string p8 = (p.Length > 8 && p[8].Trim() == "1") ? " and " + "[language].[name]='" + ci.GetLanguage().ToString() + "'" : String.Empty;//语言字段
            string p9 = (p.Length > 9 && p[9].Trim() != String.Empty) ? p[9] : String.Empty;                 //选择  
            string[][] t;
            IDataReader reader = null;

            try
            {

                int start = (p.Length > 10 && p[10].Trim() != String.Empty) ? Convert.ToInt32(p[10]) : 0;              //开始条数
                int total = (p.Length > 11 && p[11].Trim() != String.Empty) ? Convert.ToInt32(p[11]) : 0;              //条数总数

                string sql = String.Empty; //sql操作结果存储
                string wh = p9;
                string sql1 = (wh.Trim() != String.Empty ? wh.Trim() : "") + " ";
                sql1 += p8 + " ";
                string sql2 = p5 + " " + p6 + " " + p7;
                bool bWhere = (sql1.Trim() != String.Empty);
                sql = "select " + (total > 0 ? "top " + total.ToString() : "") + " " +
                    p4 + " " +
                    "from " + p[1].Trim() + (start <= 0 && !bWhere ? " " : " where ") +
                    (start > 0 ? "(" + p[2] + " not in ( select top " +
                    start.ToString() + " " + p[2] + " from " + p[1].Trim() +
                    (bWhere ? " where " + sql1 : "") + " " +
                    sql2 + ")) " + (bWhere ? "and " : " ") : "") + " " +
                    sql1 + " " + sql2;
                sql = sql.Replace("\\", "");
                ApplicationDB acsSql = new ApplicationDB(sql, ci, p3);
                reader = acsSql.ExecuteReader();
                List<string[]> a = new List<string[]>();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        string[] tt = new string[reader.FieldCount];
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            tt[i] = reader[i].ToString();
                        }
                        a.Add(tt);
                    }
                }
                else
                    return null;

                if (reader != null) reader.Close();
                t = new string[a.Count][];
                for (int ii = 0; ii < a.Count; ii++)
                    t[ii] = a[ii];
#if DEBUG
                // 操作成功,状态值
                _execStatus = 0;
#endif
                return t;
            }
            catch (Exception ex)
            {
                if (reader != null && reader.IsClosed == false) reader.Close();
#if DEBUG
                // 抛出异常
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.WebFramework.SelectRule", "选择规则错误！", ex);
            }
        }

        public string GetHelpInfo()
        {
            return " 查询记录 ";
        }

        public string GetHelpDetail()
        {
            return "从数据查询若干条记录<br/>"
                  + "例子1： { select,DMMessge,MessageID,EhaiAMS };<br/>"
                  + "例子2： { select,DMMessge, MessageID,EhaiAMS, null,null,null, LatestNodeID desc, 0,null, 1, 2 }<br/>";
        }

        public string[] GetParametersInfo()
        {
            string[] p = new string[11];
            p[0] = "（必选）处理类型 select";
            p[1] = "（必选）表名";
            p[2] = "（必选）主键，如果不为一列，则写成id1+id2";
            p[3] = "（可选) 使用的连接字符串(id)";
            p[4] = "（可选）列名，多个列名用', '隔开，默认 ' * '";
            p[5] = "（可选）分组，默认无";
            p[6] = "（可选）分组条件，默认无";
            p[7] = "（可选）排序（可多项）";
            p[8] = "（可选）是否有Language字段，1--有；0--没有";
            p[9] = "（可选）条件";
            p[10] = "（可选）开始条数";
            p[11] = "（可选）条数总数";
            return p;
        }

        #endregion
    }
}
